package com.sunedai.tiger.web.aop;

import com.google.gson.JsonObject;
import com.sunedai.tiger.common.exception.ParamsErrorException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.UnexpectedTypeException;

/**
 * 参数错误响应
 * @author zhaolipeng
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class ParamsErrorResponse {

  @ExceptionHandler({BindException.class, UnexpectedTypeException.class, ParamsErrorException.class})
  @ResponseBody
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public String errorResponse(Exception e) {
    JsonObject jsonObject = new JsonObject();
    String errorMsg;
    if (e instanceof BindException) {
      StringBuilder sb = new StringBuilder();
      BindException bindException = (BindException) e;
      for (ObjectError error : bindException.getAllErrors()) {
        sb.append(error.getDefaultMessage());
        sb.append(",");
      }
      errorMsg = sb.toString().substring(0, sb.length() - 1);
    } else if (e instanceof UnexpectedTypeException) {
      errorMsg = e.getMessage();
    } else {
      errorMsg = e.getMessage();
    }

    jsonObject.addProperty("errorMsg", errorMsg);
    log.error(jsonObject.toString());
    return jsonObject.toString();
  }
}
